<?php
namespace app\mall\controller;

use app\data\controller\api\Auth;
use app\mall\logic\ShoppingCartLogic;
use app\mall_back\model\GoodsLuckyDrawModel;

class ShoppingCart extends Auth {

    //加入购物车
    public function add_shopping_cart(){
        $id                = request()->param('id', 0);
        $purchase_quantity = request()->param('purchase_quantity', 1);

        $logic = new ShoppingCartLogic();
        $res   = $logic->add_shopping_cart($this->uuid, $id, $purchase_quantity);
        if ($res['code'] == 200) {
            $this->success($res['msg']);
        }
        $this->error($res['msg'], '', $res['code']);
    }

    //购物车列表
    public function shopping_cart_list(){
        $logic = new ShoppingCartLogic();
        $data = $logic->shopping_cart_list($this->uuid);
        $this->success('购物车列表',$data);
    }

    //删除购物车
    public function del_shopping_cart(){
        $id = request()->param('id',0);
        $logic = new ShoppingCartLogic();
        $res = $logic::del_shopping_cart($this->uuid,$id);
        if ($res) $this->success('删除购物车成功');
        $this->error('删除购物车失败','',500);
    }

    //购物车商品 增和减
    public function shopping_cart_inc_dec(){
        $id = request()->param('id',0);
        $operate = request()->param('operate',0);
        $purchase_quantity = request()->param('purchase_quantity',0);
        $logic = new ShoppingCartLogic();
        $res = $logic->shopping_cart_inc_dec($this->uuid,$id,$operate,$purchase_quantity);
        if ($res['code'] == 200) $this->success($res['msg']);
        $this->error($res['msg'],'',$res['code']);
    }

    public function batch_add_cart()
    {
        $pmax    = $this->request->param('pmax', 0);
        $pmin    = $this->request->param('pmin', 0);
        $pcnt    = $this->request->param('buy_num', 0);


        if ($pmax == 0 && $pmin == 0) {
            $this->error('非法参数：pmax - pmin', '', 500);
        }
        if (!$pcnt) {
            $this->error('预购人次不能为空', '', 500);
        }

        $query = GoodsLuckyDrawModel::alias('d');
        if ($pmin > 0) {
            $query->where('people_number', '>=', $pmin);
        }
        if ($pmax > 0) {
            $query->where('people_number', '<=', $pmax);
        }

        $draws = $query->where('status', '=', GoodsLuckyDrawModel::STATE_STARTING)
            ->select();

        $result = true;
        $logic = new ShoppingCartLogic();
        foreach ($draws as $key => $draw) {
            $res = $logic->add_shopping_cart($this->uuid, $draw->id, $pcnt);
            if ($res['code'] == 200) {
                $result &= true;
            }
        }

        $this->success('操作成功');
    }
}